package com.cpit.platform.log.aop;

import java.util.Arrays;
import java.util.Enumeration;

import javax.servlet.http.HttpServletRequest;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

@Aspect
@Component
@Order(-5)
public class WebLogAspect {
	private Logger logger = LoggerFactory.getLogger(this.getClass());

	private ThreadLocal<Long> startTime = new ThreadLocal<Long>();

	
	@Pointcut("execution(public * com..*Controller.*(..))")
	public void webLog() {
	}

	
	@Before("webLog()")
	public void doBefore(JoinPoint joinPoint) {
		startTime.set(System.currentTimeMillis());
		// 接收到请求，记录请求内容
		logger.info("WebLogAspect.doBefore()");
		ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
		HttpServletRequest request = attributes.getRequest();

		// 记录下请求内容
		logger.debug("URL : " + request.getRequestURL().toString());
		logger.debug("HTTP_METHOD : " + request.getMethod());
		logger.debug("IP : " + request.getRemoteAddr());
		logger.debug("CLASS_METHOD : " + joinPoint.getSignature().getDeclaringTypeName() + "."
				+ joinPoint.getSignature().getName());
		logger.debug("ARGS : " + Arrays.toString(joinPoint.getArgs()));

		// 获取所有参数方法一：
		Enumeration<String> enu = request.getParameterNames();
		while (enu.hasMoreElements()) {
			String paraName = (String) enu.nextElement();
			logger.debug(paraName + ": " + request.getParameter(paraName));
		}

	}

	@AfterReturning(returning = "object", pointcut = "webLog()")
	public void doAfterReturning(Object object) {

		// 处理完请求，返回内容
		logger.debug("RESPONSE : {}", object);
		logger.debug("耗时（毫秒） : {}" , (System.currentTimeMillis() - startTime.get()));

	}

}
